package com.scienview.core.context;

import java.util.concurrent.Semaphore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.method.HandlerMethod;

import com.scienview.core.anotation.Access;
import com.scienview.core.identifier.Identifier;

public class ContextHelper {
	private static Logger logger=Logger.getLogger(ContextHolder.class);
	public static void parse(HttpServletRequest request,HttpServletResponse response,HandlerMethod handler){
		Context context=new Context();
		context.request=request;
		context.response=response;
		context.handler=handler;
		regist(context);
		MySemaphore.acquire();
	
	}
	
	static void regist(Context context){
		ContextHolder.threadLocalContext.set(context);
		context.startTime=System.currentTimeMillis();
		logger.debug("uri:"+context.getRequest().getRequestURI());
	}
	public static boolean access(){
		Access access=getAccess();
		Identifier identifier=access.level();
		return identifier.identify();
	}
	
	public static  void warn(){
		Access access=getAccess();
		Identifier identifier=access.level();
		identifier.warn(access);
	}
	public static  void clear(){
		Context context=ContextHolder.getContext();
		if(context!=null)
		logger.debug(new StringBuffer("耗时：").append((System.currentTimeMillis()-context.startTime)).append("ms"));
		ContextHolder.threadLocalContext.remove();
		MySemaphore.release();
	}
	
	private static Access getAccess(){
		Context context=ContextHolder.getContext();
		Access access=context.getHandler().getMethodAnnotation(Access.class);
		if(access==null){
			throw new RuntimeException(context.getHandler().getBean().getClass()+"."+context.getHandler().getMethod().getName()+"未配置权限");
		}
		assert access!=null;
		return access;
	}
	
	/**
	 * 
	 * @author w
	 *
	 */
	private static final class MySemaphore{

		public static Semaphore instance=new Semaphore(1);
		public MySemaphore() {
		}
		
		public static void acquire(){
			try{
				instance.acquire();
			}catch(Exception e){
				e.printStackTrace();
			}
			System.out.println("<<<<<<<<<<<<<<<<");
		}
		
		public static void release(){
			instance.release();
			System.out.println(">>>>>>>>>>>>>>>");
		}

		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

	}
}
